package com.yhq.basic.thread.juc;

import java.util.concurrent.Semaphore;

/**
 * 注意
 * @author hqyin
 * @date 2025/5/9 10:54 AM
 */
public class TestSemaphore {
    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(1,true);
        Thread t1 = new Thread("t1"){
            @Override
            public void run() {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"获取到许可");
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName()+":"+Thread.currentThread().isInterrupted());
                    e.printStackTrace();
                    return;
                } finally {
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName()+"释放许可");
                }
            }
        };
        t1.start();

        Thread t2 = new Thread("t2"){
            @Override
            public void run() {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"获取到许可");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName()+",Thread.interrupted:"+Thread.interrupted());
                    System.out.println(Thread.currentThread().getName()+":"+Thread.currentThread().isInterrupted());
                    e.printStackTrace();
                    return;
                } finally {
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName()+"释放许可");
                }
            }
        };
        t2.start();
        Thread.sleep(1000);
        t2.interrupt();
        try {
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName()+"获取到许可");
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName()+":"+Thread.currentThread().isInterrupted());
            e.printStackTrace();
        } finally {
            semaphore.release();
            System.out.println(Thread.currentThread().getName()+"释放许可");
        }


    }
}
